package tech.cn.note.html.tool;

import java.math.BigDecimal;
import java.util.List;

import freemarker.template.SimpleNumber;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import tech.cn.note.utils.BigDecimalUtil;

import org.springframework.stereotype.Component;

/**
 * 动态根据参数设定小数位
 * 显示百分比
 *
 * @author liuyong
 */
@Component
public class PercentConvert implements DocumentConvert {

    //转换器名称
    public static String CONVERT_NAME = "percent";

    //默认保留两位小数
    public static int DEFAULT_POINTNUM = 2;

    @Override
    public String getConvertName() {
        return CONVERT_NAME;
    }

    @Override
    public Object exec(List params) throws TemplateModelException {
        if (params == null || params.size() < 1) {
            return "";
        }
        Object objParam = params.get(0);
        if (objParam == null) {
            return "";
        }
        int pointNum = DEFAULT_POINTNUM;
        if (params.size() > 1 && params.get(1) != null
                && StringUtils.isNotBlank(params.get(1).toString())) {
            pointNum = Integer.valueOf(params.get(1).toString());
        }
        BigDecimal numValue = null;
        if (objParam instanceof SimpleNumber) {
            numValue = new BigDecimal(objParam.toString());
        } else if (objParam instanceof SimpleScalar) {
            numValue = new BigDecimal(objParam.toString());
        } else {
            throw new TemplateModelException("模板自定义小数百分比无法识别模板中的数据类型");
        }
        return BigDecimalUtil.percentFormat(numValue, pointNum);
    }
}
